/*
 *    Copyright (c) 2018-2025, proj All rights reserved.
 *
 * Redistribution and use in source and binary forms, with or without
 * modification, are permitted provided that the following conditions are met:
 *
 * Redistributions of source code must retain the above copyright notice,
 * this list of conditions and the following disclaimer.
 * Redistributions in binary form must reproduce the above copyright
 * notice, this list of conditions and the following disclaimer in the
 * documentation and/or other materials provided with the distribution.
 * Neither the name of the proj developer nor the names of its
 * contributors may be used to endorse or promote products derived from
 * this software without specific prior written permission.
 * Author: proj
 */
package com.ykht.proj.coupon.service.impl;

import cn.hutool.core.collection.ListUtil;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.github.binarywang.wxpay.bean.entpay.EntPayRequest;
import com.github.binarywang.wxpay.bean.entpay.EntPayResult;
import com.github.binarywang.wxpay.exception.WxPayException;
import com.github.binarywang.wxpay.service.WxPayService;
import com.ykht.proj.common.core.exception.BusinessException;
import com.ykht.proj.common.security.util.SecurityUtils;
import com.ykht.proj.coupon.config.WxPayProperties;
import com.ykht.proj.coupon.entity.FxConfWithdrawal;
import com.ykht.proj.coupon.entity.FxPersonAccount;
import com.ykht.proj.coupon.entity.FxWithdrawalPerson;
import com.ykht.proj.coupon.mapper.FxPersonAccountMapper;
import com.ykht.proj.coupon.mapper.FxWithdrawalPersonMapper;
import com.ykht.proj.coupon.service.FxConfWithdrawalService;
import com.ykht.proj.coupon.service.FxPersonAccountService;
import com.ykht.proj.coupon.vo.FxPersonAccountVo;
import com.ykht.proj.coupon.vo.FxWithdrawalPersonVo;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import net.bytebuddy.implementation.bytecode.Throw;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Lazy;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import java.math.BigDecimal;
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.util.ArrayList;
import java.util.List;
import java.util.Optional;
import java.util.stream.Collectors;

/**
 * c端账户表
 *
 * @author proj code generator
 * @date 2021-08-12 14:10:39
 */
@Service
@RequiredArgsConstructor(onConstructor_ = {@Lazy, @Autowired})
@Slf4j
@Transactional
@SuppressWarnings("all")
public class FxPersonAccountServiceImpl extends ServiceImpl<FxPersonAccountMapper, FxPersonAccount> implements FxPersonAccountService {


	private final FxPersonAccountMapper fxPersonAccountMapper;
	private final FxConfWithdrawalService fxConfWithdrawalService;
	private final WxPayProperties properties;
	private final WxPayService wxService;
	private final FxWithdrawalPersonMapper fxWithdrawalPersonMapper;

	/**
	 * 分销收益有效给C端用户佣金
	 *
	 * @param personId      登录id(C端)
	 * @param type          0分销用户
	 * @param balance       可用余额
	 * @param balanceTotal  累计收益
	 * @param balanceFrozen 冻结金额
	 * @param withdrawal    累计提现金额
	 * @param updateUser    修改人
	 */
	@Override
	public void updateFxPersonAccount(Long personId, Integer type, BigDecimal balance, BigDecimal balanceTotal, BigDecimal balanceFrozen, BigDecimal withdrawal, Long updateUser) {
		fxPersonAccountMapper.updateFxPersonAccount(personId, type, balance, balanceTotal, balanceFrozen, withdrawal, updateUser);
	}

	/**
	 * 分页查询 c端账户表
	 *
	 * @param page              分页对象
	 * @param fxPersonAccountVo c端账户表
	 * @return
	 */
	@Override
	public IPage<FxPersonAccountVo> getFxPersonAccountPage(Page page, FxPersonAccountVo fxPersonAccountVo) {
		return fxPersonAccountMapper.getFxPersonAccountPage(page, fxPersonAccountVo);
	}

	/**
	 * 分页查询 c端账户提现记录列表
	 *
	 * @param page              分页对象
	 * @param fxPersonAccountVo c端账户表
	 * @return
	 */
	@Override
	public IPage<FxPersonAccountVo> getCWithdrawalRecordPage(Page page, FxPersonAccountVo fxPersonAccountVo) {
		return fxPersonAccountMapper.getCWithdrawalRecordPage(page, fxPersonAccountVo);
	}

	@Override
	@Transactional(rollbackFor = Exception.class)
	public void withdrawal(BigDecimal money) {
		log.info("->校验提现配置");
		Long loginId = SecurityUtils.getPersonId();
		FxConfWithdrawal fxConfWithdrawal = fxConfWithdrawalService.list().get(0);
		if (fxConfWithdrawal == null) throw new BusinessException("未配置体现规则");
		String[] split = fxConfWithdrawal.getGears().split(",");
		List<BigDecimal> collect = ListUtil.toList(split).stream().map(o -> new BigDecimal(o)).collect(Collectors.toList());
		if (!collect.contains(money)) throw new BusinessException("非法的提现金额");

		log.info("->校验提现金额是否大于账户余额");
		FxPersonAccount account = this.getOne(Wrappers.lambdaQuery(FxPersonAccount.class).eq(FxPersonAccount::getPersonId, loginId));
		if (account.getBalance().compareTo(money)<0) throw new BusinessException("余额不足");

		log.info("->添加提现记录");
		FxWithdrawalPerson withdrawalPerson = new FxWithdrawalPerson();
		String orderNumber = String.valueOf(System.currentTimeMillis());
		withdrawalPerson.setOrderNumber(orderNumber);
		withdrawalPerson.setPersonId(loginId);
		withdrawalPerson.setWithdrawalType(1);//提现类型：1  微信提现  2支付宝   3银行卡
		withdrawalPerson.setMoney(money);
		withdrawalPerson.setBalance(account.getBalance().subtract(money));
		withdrawalPerson.setStatus(1);//提现状态：0成功1体现中2失败
		withdrawalPerson.insert();


		log.info("->调用提现接口");
		EntPayResult entPayResult = null;
		try {
			entPayResult = this.pay(money, SecurityUtils.getPerson().getOpenId(),orderNumber);
			withdrawalPerson.setStatus(0);
			withdrawalPerson.setWxOrder(entPayResult.getPaymentNo());
//			withdrawalPerson.setSuccessTime(LocalDateTime.parse(entPayResult.getPaymentTime(), DateTimeFormatter.ISO_LOCAL_DATE_TIME));
			withdrawalPerson.setSuccessTime(LocalDateTime.now());
		} catch (WxPayException e) {
			e.printStackTrace();
			log.error("---------->提现失败,接口返回信息,{}",e.getErrCodeDes());
			log.error("---------->异常信息,接口信息,{}",e.getMessage());
			withdrawalPerson.setStatus(2);
			throw new BusinessException(e.getErrCodeDes());
		}
		log.info("->更新提现信息");
		withdrawalPerson.updateById();
		log.info("->扣减余额");
		if (withdrawalPerson.getStatus() == 0){
			fxPersonAccountMapper.updateFxPersonAccount(loginId,0,money.negate(),null,BigDecimal.ZERO,money,loginId);
		}
	}

	@Override
	public List<FxWithdrawalPersonVo> getExport() {
		return fxWithdrawalPersonMapper.getExport();
	}

	@Override
	public List<FxPersonAccountVo> ExportExcelPerson() {
		return fxPersonAccountMapper.ExportExcelPerson();
	}

	EntPayResult pay(BigDecimal money,String openId,String orderNumber) throws WxPayException {
		EntPayRequest entPay = new EntPayRequest();
		entPay.setMchAppid(properties.getMchAppid());
		entPay.setMchId(properties.getMchId());
		entPay.setDeviceInfo("");//
		entPay.setPartnerTradeNo(orderNumber);
//		entPay.setOpenid("oZv-S4qfEHHeKu5VUKeUfjEbE98o");
		entPay.setOpenid(openId);
		entPay.setCheckName("NO_CHECK");//
		entPay.setCheckName(properties.getCheckName());
		entPay.setReUserName("");
		entPay.setAmount(money.multiply(new BigDecimal("100")).intValue());
		entPay.setDescription("吃哈哈佣金提现");//

		System.out.println("*****************************************************************");
		System.out.println("*****************************************************************");
		System.out.println("**********************"+openId+"*********************************");
		entPay.setSpbillCreateIp(properties.getSpbillCreateIp());//
		EntPayResult entPayResult = wxService.getEntPayService().entPay(entPay);
		return entPayResult;
	}

}
